<?php

namespace app\merchant\model\dealer;

use app\common\model\dealer\Order as OrderModel;
use app\common\service\Order as OrderService;

/**
 * 分销商订单模型
 * Class Apply
 * @package app\store\model\dealer
 */
class Order extends OrderModel
{
    /**
     * 获取分销商订单列表
     * @param null $user_id
     * @param int $is_settled
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($user_id = null, $is_settled = -1,$order_type = -1,$search)
    {

        // 检索查询条件
        $user_id > 1 && $this->where('first_user_id|second_user_id|third_user_id', '=', $user_id);
        $is_settled > -1 && $this->where('is_settled', '=', $is_settled);
        $order_type > -1 && $this->where('order_type', '=', $order_type);

        if (!is_null($search) && isset($search)) {
            $this->where('user.nickName', 'like', '%' . trim($search) . '%');
        }
        // 获取分销商订单列表
        $data = $this->alias('order')
            ->join('user user','order.user_id=user.user_id')
            ->with([
            'dealer_first.user',
            'dealer_second.user',
            'dealer_third.user'
        ])
            ->order(['order.create_time' => 'desc'])
            ->paginate(10, false, [
                'query' => \request()->request()
            ]);
        if ($data->isEmpty()) {
            return $data;
        }

        // 获取订单的主信息
        $with = ['goods' => ['image', 'refund'], 'address'];
        $with2 = ['orderplan' => ['image'], 'address'];
        $with3 = ['goods' => ['image']];

        return OrderService::getOrderList($data, 'order_master', $with,$with2,$with3);
    }


    /**
     * 设置检索查询条件
     * @param $query
     */
    private function setWhere($query)
    {

        if (isset($query['search']) && !empty($query['search'])) {
            $this->where('buyuser.nickName|firstuser.nickName', 'like', '%' . trim($query['search']) . '%');
        }

        if (isset($query['start_time']) && !empty($query['start_time'])) {
            $this->where('order.settle_time', '>=', strtotime($query['start_time']));
        }
        if (isset($query['end_time']) && !empty($query['end_time'])) {
            $this->where('order.settle_time', '<', strtotime($query['end_time']) + 86400);
        }
        if (isset($query['order_type']) && !empty($query['order_type'])) {
            $query['order_type'] > -1 && $this->where('order.order_type', '=', $query['order_type']);
        }


    }


    /**
     * 获取分销商订单列表
     * @param null $user_id
     * @param int $is_settled
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getFinanceList($query = [])
    {

        // 检索查询条件
        !empty($query) && $this->setWhere($query);

        $where = ['order.is_settled'=>1];
        //获取分销订单列表
        $data = $this->alias('order')
            ->join('user buyuser','order.user_id=buyuser.user_id')
            ->join('user firstuser','order.first_user_id=firstuser.user_id')
            ->field('
            order.id,order.user_id,order.order_id,order.order_type,order.order_price,order.first_user_id,order.first_money,order.is_settled,order.settle_time,order.wxapp_id,buyuser.user_id as buyuser_id,buyuser.nickName as buyuser_nickName,firstuser.user_id as firstuser_id,firstuser.nickName as firstuser_nickName
            ')
            ->order(['order.create_time' => 'desc'])
            ->where($where)
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
        if ($data->isEmpty()) {
            return [];
        }

        // 获取订单的主信息
        $with = ['goods' => ['image']];
        $with2 = ['orderplan' => ['image']];
        $with3 = ['goods' => ['image']];

        return OrderService::getOrderList($data, 'order_master', $with,$with2,$with3);
    }




    /**
     * 财务管理分销订单导出
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function deaclerFinanceExport($query = [])
    {

        header("Content-type:text/html;charset=utf-8");
        $mpName = '分销订单';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = $this->getDeaclerFinanceExport($query,0, $limit,true);

        if($sqlCount<1){
            $this->error = '无数据导出';
            return false;
        }

        $xlsTitle = [
            '订单编号', '订单类型','商品信息', '订单总额',
            '实付款金额', '下单时间', '买家', '分销商', '分销金额','付款状态','付款时间'
        ];

        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->getDeaclerFinanceExport($query, $start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件

    }


    /**
     * 财务管理储值订单导出列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getDeaclerFinanceExport($query = [],$start, $limit,$count = false)
    {

        // 检索查询条件
        !empty($query) && $this->setWhere($query);

        $where = ['order.is_settled'=>1];

        if($count==true){
            // 获取数据列表
            return $this->alias('order')
                ->join('user buyuser','order.user_id=buyuser.user_id')
                ->join('user firstuser','order.first_user_id=firstuser.user_id')
                ->field('
            order.id,order.user_id,order.order_id,order.order_type,order.order_price,order.first_user_id,order.first_money,order.is_settled,order.settle_time,order.wxapp_id,buyuser.user_id as buyuser_id,buyuser.nickName as buyuser_nickName,firstuser.user_id as firstuser_id,firstuser.nickName as firstuser_nickName
            ')
                ->order(['order.create_time' => 'desc'])
                ->where($where)
                ->count();
        }

        // 获取分销商订单列表
        $data = $this->alias('order')
            ->join('user buyuser','order.user_id=buyuser.user_id')
            ->join('user firstuser','order.first_user_id=firstuser.user_id')
            ->field('
            order.id,order.user_id,order.order_id,order.order_type,order.order_price,order.first_user_id,order.first_money,order.is_settled,order.settle_time,order.wxapp_id,buyuser.user_id as buyuser_id,buyuser.nickName as buyuser_nickName,firstuser.user_id as firstuser_id,firstuser.nickName as firstuser_nickName
            ')
            ->order(['order.create_time' => 'desc'])
            ->where($where)
            ->limit($start,$limit)
            ->select();

        if ($data->isEmpty()) {
            return $data;
        }

        // 获取订单的主信息
        $with = ['goods' => ['image']];
        $with2 = ['orderplan' => ['image']];
        $with3 = ['goods' => ['image']];

        $list =  OrderService::getOrderList($data, 'order_master', $with,$with2,$with3);

        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {

            switch ($order['order_type']['value']){
                case "10"://普通订单

                    $goodsInfo = $this->filterGoodsInfo($order);
                    $total_price = $order['order_master']['total_price'];
                    $coupon_money = $order['order_master']['coupon_money'];
                    $balance_money = $order['order_master']['balance_money'];
                    break;
                case "30"://储值卡订单
                    $goodsInfo= $this->filterCardInfo($order);
                    $total_price = $order['order_master']['total_price'];
                    $coupon_money = 0;
                    $balance_money = 0;
                    break;
                case "40"://购买爆品礼
                    $goodsInfo = $this->filterGiftsInfo($order);
                    $total_price = $order['order_master']['order_price'];
                    $coupon_money = 0;
                    $balance_money = 0;
                    break;
                case "50"://当面付
                    $goodsInfo= "---";
                    $total_price = $order['order_master']['total_price'];
                    $coupon_money = $order['order_master']['coupon_money'];
                    $balance_money = $order['order_master']['balance_money'];
                    break;
                case "60"://分红转化
                    $goodsInfo= "---";
                    $total_price = $order['order_master']['total_price'];
                    $coupon_money = 0;
                    $balance_money = 0;
                    break;
                case "5"://大额支付
                    $goodsInfo= "---";
                    $total_price = $order['order_master']['pay_price'];
                    $coupon_money = 0;
                    $balance_money = 0;
                    break;

            }

            $dataArray[] = [
                '订单编号' => $this->filterValue($order['order_master']['order_no']),
                '订单类型' => $this->filterValue($order['order_type']['text']),
                '商品信息' => $goodsInfo,
                '订单总额' => $this->filterValue($total_price),
                '实付款金额' => $this->filterValue($order['order_master']['pay_price']),
                '下单时间' => $this->filterValue($order['order_master']['create_time']),
                '买家' => $this->filterValue($order['buyuser_nickName']),
                '分销商' => $this->filterValue($order['firstuser_nickName']),
                '分销金额' => $this->filterValue($order['first_money']),
                '付款状态' => $this->filterValue($order['order_master']['pay_status']['text']),
                '付款时间' => $this->filterTime($order['order_master']['pay_time']),

            ];
        }

        return  $dataArray;


    }


    /**
     * 格式化商品信息
     * @param $order
     * @return string
     */
    private function filterCardInfo($order)
    {

        $content = '';
        $content .= ".商品名称：{$order['order_master']['orderplan']['card_title']}\n";
        $content .= "　购买数量：1\n";
        $content .= "　商品总价：{$order['order_master']['orderplan']['card_real_money']}元\n\n";
        return $content;
    }


    /**
     * 格式化商品信息
     * @param $order
     * @return string
     */
    private function filterGiftsInfo($order)
    {

        $content = '';
        foreach ($order['order_master']['goods'] as $key => $goods) {
            $content .= ($key + 1) . ".商品名称：{$goods['gifts_title']}\n";
            $content .= "　购买数量：1\n";
            $content .= "　商品总价：{$goods['gifts_price']}元\n\n";
        }
        return $content;
    }


    /**
     * 格式化商品信息
     * @param $order
     * @return string
     */
    private function filterGoodsInfo($order)
    {

        $content = '';
        foreach ($order['order_master']['goods'] as $key => $goods) {
            $content .= ($key + 1) . ".商品名称：{$goods['goods_name']}\n";
            !empty($goods['goods_attr']) && $content .= "　商品规格：{$goods['goods_attr']}\n";
            $content .= "　购买数量：{$goods['total_num']}\n";
            $content .= "　商品总价：{$goods['total_price']}元\n\n";
        }
        return $content;
    }

    /**
     * 表格值过滤
     * @param $value
     * @return string
     */
    private function filterValue($value)
    {
        return "\t" . $value . "\t";
    }


    /**
     * 日期值过滤
     * @param $value
     * @return string
     */
    private function filterTime($value)
    {

        if (!$value) return '';
        return $this->filterValue(date('Y-m-d H:i:s', $value));
    }

}